package co.liyao.controller;

import co.liyao.dto.RoleDto;
import co.liyao.dto.UserOnlineVo;
import co.liyao.mapper.UserRoleMapper;
import co.liyao.model.User;
import co.liyao.service.UserService;
import co.liyao.shiro.realm.UserRealm;
import co.liyao.util.JsonData;
import co.liyao.util.PageResultVo;
import co.liyao.util.PasswordHelper;
import co.liyao.util.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: liyao
 * @Date: 2019/2/21 13:11
 * @Description:
 */
@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private UserRealm userRealm;



    /**用户列表数据*/
    @GetMapping("/list")
    @ResponseBody
    public PageResultVo loadUsers(User user, Integer limit, Integer page){
        PageHelper.startPage(page,limit);
        List<User> userList = userService.selectUsers(user);
        PageInfo<User> pages = new PageInfo<>(userList);
        return JsonData.table(userList,pages.getTotal());
    }

    @GetMapping("/roleList")
    @ResponseBody
    public PageResultVo roleList(Integer id){
        List<RoleDto> selectedRoleByUserId = userService.findSelectedRoleByUserId(id);
        return JsonData.table(selectedRoleByUserId);
    }

    /**
     *  更改用户的角色
     * @param userid
     * @param roleid
     * @return
     */
    @PostMapping("/updateRoleIdbyUserId")
    @ResponseBody
    public JsonData roleList(final Integer userid, final Long[] roleid){
        userService.updateRoleIdbyUserId(userid,roleid);
        Subject subject= SecurityUtils.getSubject();
        List<String> useridList = new ArrayList<>();
        useridList.add(String.valueOf(userid));
        userRealm.clearAuthorizationByUserId(useridList);  // 清除缓存的角色
        return JsonData.success();
    }

    /**编辑用户详情*/
    @GetMapping("/edit")
    public String userDetail(Model model, String userId){
        User user = userService.selectByUserId(userId);
        model.addAttribute("user", user);
        return "user/userDetail";
    }

    /**编辑用户*/
    @PostMapping("/edit")
    @ResponseBody
    public JsonData editUser(User userForm){
        int a = userService.updateByUserId(userForm);
        if (a > 0) {
            return JsonData.success(null,"编辑用户成功！");
        } else {
            return JsonData.fail("编辑用户失败");
        }
    }

    /**编辑用户*/
    @PostMapping("/del")
    @ResponseBody
    public JsonData delUser(String userId){
        try{
            userService.del(Integer.parseInt(userId));
        }catch(Exception ex){
            JsonData.fail("出现错误");
        }
        return JsonData.success(null,"删除成功");
    }

    /**新增用户*/
    @PostMapping("/add")
    @ResponseBody
    public JsonData add(User userForm, String confirmPassword){
        String username = userForm.getUsername();
        User user = userService.selectByUsername(username);
        if (null != user) {
            return JsonData.fail("用户名已存在");
        }
        String password = userForm.getPassword();
        //判断两次输入密码是否相等
        if (confirmPassword != null && password != null) {
            if (!confirmPassword.equals(password)) {
                return JsonData.fail("两次密码不一致");
            }
        }
        userForm.setUserId(UUIDUtil.getUniqueIdByUUId());
        userForm.setStatus(1);
        Date date = new Date();
        userForm.setCreateTime(date);
        userForm.setUpdateTime(date);
        userForm.setLastLoginTime(date);
        PasswordHelper.encryptPassword(userForm);
        int num = userService.register(userForm);
        if(num > 0){
            return JsonData.success(null,"添加用户成功");
        }else {
            return JsonData.fail("添加用户失败");
        }
    }

}
